//    Copyright (C) Kherty.  All rights reserved.
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace OpenLS.UI.Themes
{
    partial class ToolTipResources
    {
        public ToolTipResources()
        {
            InitializeComponent();
        }

        private void onToolTipLoaded(object sender, object args)
        {
            var tt = (ToolTip) sender;
            tt.Placement = PlacementMode.Custom;
            tt.CustomPopupPlacementCallback = delegate
                (Size popupSize, Size targetSize, Point offset) { return placeRibbonToolTip(tt, popupSize, targetSize, offset); };
        }

        private static CustomPopupPlacement[] placeRibbonToolTip(ToolTip tt, Size popupSize, Size targetSize,
                                                                Point offset)
        {
            var placementTarget = tt.PlacementTarget as FrameworkElement;
            var ribbon = WindowServices.GetAncestor<Ribbon>(placementTarget);
            double naN = double.NaN;
            double y = double.NaN;
            if ((ribbon != null) && ribbon.IsAncestorOf(tt.PlacementTarget))
            {
                var transform = ribbon.TransformToDescendant(tt.PlacementTarget) as MatrixTransform;
                if (transform != null)
                {
                    naN = (ribbon.ActualHeight + 5.0) + transform.Value.OffsetY;
                    y = transform.Value.OffsetY - tt.ActualHeight;
                }
            }
            else
            {
                return new[] {new CustomPopupPlacement(new Point(0.0, tt.ActualHeight), PopupPrimaryAxis.Vertical)};
            }
            var placement = new CustomPopupPlacement(new Point(0.0, naN), PopupPrimaryAxis.Vertical);
            var placement2 = new CustomPopupPlacement(new Point(0.0, y), PopupPrimaryAxis.Vertical);
            return new[] {placement, placement2};
        }
    }
}